import { useEffect, useState, forwardRef, useImperativeHandle, useMemo } from 'react'
import { Form, Tree, message } from 'antd'

import request from '@/utils/request'
import { IForm } from '@/components'
import { roleTypeMap } from '@/utils/consts'
import { useAppSelector } from '@/utils/hooks'
import { transformTreeData } from '@/utils/util'

import type { FormItemConfig } from '@/components/FormItem'
import { RecordItem } from '../type'

interface Props {
  selRecord?: RecordItem
}

const AuthForm = forwardRef((props: Props, ref) => {
  const [form] = Form.useForm()
  const { currentEntity, userInfo } = useAppSelector(state => state.app)
  const [roleType, setRoleType] = useState()
  const [regions, setRegions] = useState<DataNode[]>([])
  const [enterpriseOpts, setEnterpriseOpts] = useState([])
  const [rolesUnionResources, setRolesUnionResources] = useState([])

  useEffect(() => {
    if (props.selRecord) {
      queryAuthDetail()
    }
  }, [props.selRecord])

  useImperativeHandle(ref, () => ({
    validateFields: () => {
      return form.validateFields().catch((error: any) => {
        message.warn('请完善用户授权信息')
        throw error
      })
    },
  }))

  useEffect(() => {
    if (roleType == roleTypeMap.enterpriseRole) {
      // queryEnterpriseOpts()
    }
  }, [roleType])

  useEffect(() => {
    if (currentEntity.entityId && !props.selRecord) {
      // queryEntityRegion()
    }
  }, [currentEntity, props.selRecord])

  const queryAuthDetail = () => {
    request('userManageQueryAuthDetail', { data: { userId: props.selRecord?.id } }).then(
      res => {
        if (res.code === 0 && res.data) {
          form.setFieldsValue({ ...res.data })
          setRoleType(res.data.roleType)
          queryRolesUnionResources(res.data.roleIds)
          queryEntityRegion()
        }
      }
    )
  }

  const queryEnterpriseOpts = () => {
    // const isCompany = userInfo.roleType === roleTypeMap.enterpriseRole
    const data = {
      // entityId: currentEntity.entityId,
      // companyId: isCompany ? userInfo.companyId : undefined,
    }
    request('commonQueryEnterpriseOpts', { data }).then(res => {
      if (res.code === 0 && res.data) {
        setEnterpriseOpts(res.data)
      }
    })
  }

  const queryEntityRegion = () => {
    const data = {
      // entityId: currentEntity.entityId,
    }
    // request('commonQueryEntityRegion', { data }).then(res => {
    //   if (res.code === 0 && res.data) {
    //     setRegions(
    //       transformTreeData(res.data, node => ({ isLeaf: !node.hasChildren }), 'adName', 'adCode')
    //     )
    //   }
    // })
  }

  const queryRolesUnionResources = (value: any[]) => {
    const data = {
      tenantId: currentEntity.entityId,
      roleIds: value,
    }
    request('userManageRolesUnionResources', { data }).then(res => {
      if (res.code === 0 && res.data) {
        form.setFieldsValue({ resourceList: res.data })
        // setRolesUnionResources(transformTreeData(res.data, 'label', 'value'))
        setRolesUnionResources((res.data))
      }
    })
  }

  const handleRoleTypeChange = (value: any[]) => {
    queryRolesUnionResources(value)
  }

  const roleSelectExtraData = useMemo(() => {
    return { roleType }
  }, [roleType])

  const formItemsConfig: FormItemConfig[] = [
    {
      type: 'roleTypeSelect',
      formItemProps: {
        label: '用户类型',
        name: 'roleType',
        rules: [{ required: true }],
      },
      childProps: {
        onChange(value) {
          setRoleType(value)
          setRolesUnionResources([])
          form.setFieldsValue({ adCodeList: [], companyId: undefined, roleIds: [] })
        },
      },
    },
    // roleType == roleTypeMap.platformRole
    //   ? {
    //       type: 'radioGroup',
    //       formItemProps: {
    //         label: '是否三方',
    //         name: 'thirdPartyFlag',
    //         rules: [{ required: true }],
    //         initialValue: 0,
    //         extra: '说明: 三方公司用户负责清运、扣车等执行动作，支持在任务中心认领并处理超时工单。',
    //       },
    //       childProps: {
    //         options: [
    //           { label: '普通平台用户', value: 0 },
    //           { label: '三方公司用户', value: 1 },
    //         ],
    //       },
    //     }
    //   : null,
    roleType != roleTypeMap.enterpriseRole
      ? {
          type: 'areaTreeSelect',
          formItemProps: {
            label: '数据范围',
            name: 'adCodeList',
            rules: [{ required: true }],
          },
          childProps: {
            // disabled: roleType == roleTypeMap.enterpriseRole,
            treeCheckable: true,
            multiple: true,
            treeData: regions,
          },
        }
      : null,
    {
      type: 'roleSelect',
      extraData: roleSelectExtraData,
      formItemProps: {
        label: '用户角色',
        name: 'roleIds',
        rules: [{ required: true }],
      },
      childProps: {
        mode: 'multiple',
        onChange(value) {
          handleRoleTypeChange(value)
        },
      },
    },
    {
      type: 'select',
      itemRender() {
        return (
          !!rolesUnionResources.length && (
            <Form.Item label="资源点" name="resourceList" rules={[{ required: true }]}>
              <Tree selectable={false} defaultExpandAll treeData={rolesUnionResources}></Tree>
            </Form.Item>
          )
        )
      },
    },
  ]

  return <IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm>
})

AuthForm.displayName = 'AuthForm'

export default AuthForm
